<template>
  <div class="chat-messages" ref="messageContainer" @scroll="handleScroll">
    <!-- 加载更多 -->
    <div v-if="loading" class="loading-more">
      <a-spin size="small" />
    </div>

    <!-- 消息列表 -->
    <template v-for="msg in activeMessages" :key="msg.id">
      <div :class="['msg', { self: msg.from_id === userinfo.email }]">
        <div class="msg-row">
          <template v-if="msg.from_id !== userinfo.email">
            <UserAvatarCard
              :avatar="friends.get(msg.from_id)?.avatar || ''"
              :username="friends.get(msg.from_id)?.name || ''"
              :email="friends.get(msg.from_id)?.email || ''"
              :size="32"
            />
            <div class="msg-content">
              <div class="msg-header">
                <div class="msg-time">
                  {{ msg.send_at }}
                </div>
                <!-- <span class="msg-status" v-if="msg.from_id === userinfo.email">
                  <a-spin v-if="msg.status === 'sending'" size="small" />
                  <check-outlined v-else-if="msg.status === 'sent'" />
                  <check-circle-outlined v-else-if="msg.status === 'read'" style="color: #1890ff" />
                  <exclamation-circle-outlined
                    v-else-if="msg.status === 'error'"
                    style="color: red; cursor: pointer;"
                    @click.stop="chatStore.handleResend(msg)"
                  />
                </span> -->
              </div>
              <template v-if="msg.type === 'text'">
                <div class="bubble">
                  {{ msg.text }}
                </div>
              </template>
              <template v-else-if="msg.type === 'image'">
                <div class="image-wrapper">
                  <img 
                    :src="msg.image.path" 
                    class="msg-img" 
                    @click="handleImageClick(msg.id)"
                  />
                  <a-dropdown v-model:open="dropdownStates[msg.id]" trigger="click">
                    <div class="image-overlay"></div>
                    <template #overlay>
                      <a-menu @click="handleMenuClick($event, msg)">
                        <a-menu-item key="favorite">
                          <template #icon>
                            <star-outlined />
                          </template>
                          添加到表情
                        </a-menu-item>
                        <a-menu-item key="preview">
                          <template #icon>
                            <eye-outlined />
                          </template>
                          查看大图
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </div>
              </template>

            </div>
          </template>
          <template v-else>
            <div class="msg-content">
                <div class="msg-bubble-time-wrapper">
                <div class="msg-time">
                  {{ msg.send_at }}
                </div>
              <div class="msg-content-row">
                <template v-if="msg.type === 'text'">
                  <span class="msg-status" v-if="msg.from_id === userinfo.email">
                    <a-spin v-if="msg.status === 'sending'" size="small" />
                    <check-outlined v-else-if="msg.status === 'sent'" />
                    <check-circle-outlined v-else-if="msg.status === 'read'" style="color: #1890ff" />
                    <exclamation-circle-outlined
                      v-else-if="msg.status === 'error'"
                      style="color: red; cursor: pointer;"
                      @click.stop="chatStore.handleResend(msg)"
                    />
                  </span>
                  <div class="bubble self">
                    {{ msg.text }}
                  </div>
                </template>
              <template v-else-if="msg.type === 'image'">
                <span class="msg-status" v-if="msg.from_id === userinfo.email">
                  <a-spin v-if="msg.status === 'sending'" size="small" />
                  <check-outlined v-else-if="msg.status === 'sent'" />
                  <check-circle-outlined v-else-if="msg.status === 'read'" style="color: #1890ff" />
                  <exclamation-circle-outlined
                    v-else-if="msg.status === 'error'"
                    style="color: red; cursor: pointer;"
                    @click.stop="chatStore.handleResend(msg)"
                  />
                </span>
                <div class="image-wrapper">
                  <img 
                    :src="msg.image.path" 
                    class="msg-img" 
                    @click="handleImageClick(msg.id)"
                  />
                  <a-dropdown v-model:open="dropdownStates[msg.id]" trigger="click">
                    <div class="image-overlay"></div>
                    <template #overlay>
                      <a-menu @click="handleMenuClick($event, msg)">
                        <a-menu-item key="favorite">
                          <template #icon>
                            <star-outlined />
                          </template>
                          添加到表情
                        </a-menu-item>
                        <a-menu-item key="preview">
                          <template #icon>
                            <eye-outlined />
                          </template>
                          查看大图
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </div>
              </template>

              </div>
            </div>
            </div>
            <UserAvatarCard
              :avatar="userinfo.avatar"
              :username="userinfo.name"
              :email="userinfo.email"
              :size="32"
            />
          </template>
        </div>
      </div>
    </template>

    <a-modal
      v-model:open="showImageDialog"
      :footer="null"
      :centered="true"
      :width="800"
      @cancel="showImageDialog = false"
    >
      <img :src="bigImageSrc" style="max-width: 100%; max-height: 80vh; display: block; margin: 0 auto;" />
    </a-modal>
  </div>
</template>

<script setup>
import UserAvatarCard from './UserAvatarCard.vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { StarOutlined, EyeOutlined, CheckOutlined, CheckCircleOutlined } from '@ant-design/icons-vue'
import { useChatStore } from '@/stores/chat'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore();

const chatStore = useChatStore();
const {
    userinfo,
    friends,
    sessionList,
    activeMessages,
} = storeToRefs(chatStore);
const dropdownStates = reactive({})

const messageContainer = ref(null)
const loading = ref(false)
const page = ref(1)
const hasMore = ref(true)

// 监听消息列表变化，自动滚动到底部
watch(() => activeMessages.value, () => {
  scrollToBottom()
}, { deep: true })

// 滚动到底部
function scrollToBottom() {

  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    }
  })
}

// 处理滚动加载更多
function handleScroll(e) {
  const { scrollTop } = e.target
  // 当滚动到顶部时加载更多
  if (scrollTop === 0 && !loading.value && hasMore.value) {
    const height = messageContainer.value.scrollHeight
    const top = messageContainer.value.scrollTop
    loadMoreMessages().then(() => {
      messageContainer.value.scrollTop =  messageContainer.value.scrollHeight - height;
    })
  }
}

// 加载更多消息
async function loadMoreMessages() {
  if (loading.value || !hasMore.value) return
  
  loading.value = true
  try {
    const response = await chatStore.loadMoreMessages()
    if (!response.success) {
      if (response.message === '没有更多消息了') {
        hasMore.value = false
      }
    } else {
      hasMore.value = response.hasMore
    }
  } catch (error) {
    console.error('加载更多消息失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
    scrollToBottom()
})

const showImageDialog = ref(false)
const bigImageSrc = ref('')

function showBigImage(src) {
  bigImageSrc.value = src
  showImageDialog.value = true
}

function handleImageClick(msgId) {
  dropdownStates[msgId] = true
}

function handleMenuClick({ key }, msg) {
  if (key === 'favorite') {
    chatStore.handleAddFavorite(msg.image)
  } else if (key === 'preview') {
    showBigImage(msg.image.path)
  }
  dropdownStates[msg.id] = false
}
</script>

<style scoped>
.status-content {
  display: flex;
  flex-direction: row;
  align-items: flex-end; /* 让子元素底部对齐 */
  gap: 8px; /* 内容和状态之间的间距，可选 */
}
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #f9f9f9;
}
.msg {
  margin-bottom: 12px;
  display: flex;
  flex-direction: column;
}
.msg.self {
  align-items: flex-end;
}
.msg-row {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  max-width: 60vw;
}
.msg-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  min-width: 0;
  max-width: 100%;
}
.msg-time {
  text-align: right;
  color: #999;
  font-size: 12px;
  margin-bottom: 2px;
  padding-right: 8px;
  
}
.msg-bubble-time-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-end; /* 让时间和气泡右对齐 */
}
.msg-status {
  min-width: 24px;
  display: flex;
  align-items: flex-end;
  margin-right: 0px;
}
.msg-content-row {
  display: flex;
  align-items: flex-end; /* 底部对齐 */
}
.bubble {
  background: #fff;
  border-radius: 6px;
  padding: 8px 16px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.04);
  word-break: break-all;
  white-space: pre-wrap;
  overflow-wrap: break-word;
  overflow-x: hidden;
  margin-top: 2px;
  text-align: left;
  margin-left: 6px; /* 为状态图标留出空间 */
}
.bubble.self {
  background: #95ec69;
}
.image-wrapper {
  position: relative;
  display: inline-block;
  margin-left: 6px; /* 为状态图标留出空间 */
}

.msg-status {
  display: flex;
  align-items: center;
  margin-right: 4px;
}

.image-wrapper .msg-status {
  position: absolute;
  left: -6px;
  bottom: 0;
  display: flex;
  align-items: center;
}
.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  cursor: pointer;
}
.msg-img {
  max-width: 180px;
  max-height: 180px;
  border-radius: 6px;
  display: block;
  margin-top: 2px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}
.msg-file {
  color: #1890ff;
  text-decoration: underline;
  word-break: break-all;
  display: block;
  margin-top: 2px;
}
.loading-more {
  text-align: center;
  padding: 10px 0;
}
</style>